package com.sunyard.authorization.exception.resolver;

import com.sunyard.response.Response;
import org.apache.shiro.ShiroException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
//处理全局异常
public class ExceptionController {
    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public Response handleShiroException(ShiroException e, HttpServletResponse response) {
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        return Response.fail(e.getMessage());
    }

    // 捕捉其他所有异常
    @ExceptionHandler(AuthenticationException.class)
    public Response globalException(HttpServletResponse response, Throwable ex) {
        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        return Response.fail(ex.getMessage());
    }
}
